﻿using System;
using System.Collections.Specialized;
using RAP.Framework.Libary.JSON.Conversion;

namespace RAP.Framework.Libary.JSON
{
    /// <summary>
    /// JSON键值对象，键是有序排列的
    /// Hainee
    /// 2015
    /// </summary>
	public class JsonDictionary : ListDictionary, IJsonImportable, IJsonExportable
	{
		#region JSON接口
		public void Export ( ExportContext context, JsonWriter writer )
		{
			if ( context == null )
				throw new ArgumentNullException ( "context" );

			if ( writer == null )
				throw new ArgumentNullException ( "writer" );

			writer.WriteStartObject ( );

			foreach ( object key in this.Keys )
			{
				writer.WriteMember ( key.ToString ( ) );
				context.Export ( this[ key ], writer );
			}

			writer.WriteEndObject ( );
		}

		public override string ToString ( )
		{
			JsonTextWriter writer = new JsonTextWriter ( );
			this.Export ( writer );
			return writer.ToString ( );
		}

		public void Export ( JsonWriter writer )
		{
			this.Export ( new ExportContext ( ), writer );
		}

		public void Import ( JsonReader reader )
		{
			this.Import ( new ImportContext ( ), reader );
		}

		void IJsonImportable.Import ( ImportContext context, JsonReader reader )
		{
			this.Import ( context, reader );
		}

		public virtual void Import ( ImportContext context, JsonReader reader )
		{
			if ( context == null )
				throw new ArgumentNullException ( "context" );

			if ( reader == null )
				throw new ArgumentNullException ( "reader" );

			this.Clear ( );
			reader.ReadToken ( JsonTokenClass.Object );
			while ( reader.TokenClass != JsonTokenClass.EndObject )
			{
				this.Add ( reader.ReadMember ( ), context.Import ( reader ) );
			}
			reader.Read ( );
		}
		#endregion

		
	}
}
